package edu.ucdavis.gwt.gis.client.query;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Widget;

public class StatusPanel extends Composite {

	private static StatusPanelUiBinder uiBinder = GWT.create(StatusPanelUiBinder.class);
	interface StatusPanelUiBinder extends UiBinder<Widget, StatusPanel> {}

	@UiField HTML queriesReturned;
	@UiField HTML showing;
	@UiField Anchor next;
	@UiField HTML nextSpacer;
	@UiField Anchor previous;
	@UiField HTML previousSpacer;
	@UiField Anchor settings;
	
	private int total = 0;
	private int returned = 0;
	private int current = 0;
	
	public interface NavHandler {
		public void onNavigate(int featureNum);
	}
	private NavHandler handler = null;
	
	public StatusPanel() {
		initWidget(uiBinder.createAndBindUi(this));
		
		next.addClickHandler(new ClickHandler(){
			@Override
			public void onClick(ClickEvent event) {
				current++;
				updateShowing(current+1);
				if( handler != null ) handler.onNavigate(current);
				updateNav();
			}
		});
		
		previous.addClickHandler(new ClickHandler(){
			@Override
			public void onClick(ClickEvent event) {
				current--;
				updateShowing(current+1);
				if( handler != null ) handler.onNavigate(current);
				updateNav();
			}
		});
		
		settings.addClickHandler(new ClickHandler(){
			@Override
			public void onClick(ClickEvent event) {
				QueryToolSettings.INSTANCE.center();
			}
		});
		
	}
	
	public void reset() {
		setQueriesReturned(0);
		updateShowing(1);
		current = 0;
	}
	
	public int getTotal() {
		return total;
	}
	
	private void updateShowing(int num) {
		showing.setText(" Feature "+num+" of "+returned);
	}
	
	public void setNavHandler(NavHandler handler) {
		this.handler = handler;
	}
	
	public void setTotal(int total) {
		this.total = total;
	}
	
	public void setQueriesReturned(int returned) {
		queriesReturned.setText(returned+" of "+total);
	}
	
	public void setFeaturesReturned(int returned) {
		this.returned = returned;
		updateShowing(current+1);
		updateNav();
	}
	
	public void updateNav() {
		previous.setVisible(current > 0);
		previousSpacer.setVisible(current > 0);
		next.setVisible(current < returned-1);
		nextSpacer.setVisible(current < returned-1);
	}
	


}
